<template>
  <div class="app-container">
    <el-dialog :visible.sync="sumterdialogVisible" width="30%">
      <el-form label-position="left" :model="readerForm" label-width="100px" ref="readerForm">
        <el-form-item label="任务名称" prop="jobName">
          <el-input v-model="readerForm.jobName" />
        </el-form-item>
        <el-form-item label="任务目录" prop="directoryId">
          <el-select v-model="readerForm.directoryId" clearable placeholder="请选择" @clear="handleClear" ref="selectUpResId">
            <!-- // 设置一个隐藏的下拉选项
            // 如果不设置一个下拉选项，下面的树形组件将无法正常使用 -->
            <el-option hidden :value="readerForm.directoryId" :label="upResName"> </el-option>
            <!-- // 设置树形组件
              是否在点击节点的时候展开或者收缩节点， 默认值为 true，如果为 false，则只有点箭头图标的时候才会展开或者收缩节点。
              // 是否在点击节点的时候选中节点，默认值为 false，即只有在点击复选框时才会选中节点。
                // 节点被点击时的回调 -->
            <el-tree :data="treeList" :props="treeProps" :expand-on-click-node="false" :check-on-click-node="true" @node-click="handleNodeClick"> </el-tree>
          </el-select>
        </el-form-item>
        <el-form-item label="任务描述" prop="description">
          <el-input v-model="readerForm.description" />
        </el-form-item>
        <!--          <el-form-item label="上传附件" prop="filePath">-->
        <!--            <el-input v-model="readerForm.filePath" />-->
        <!--          </el-form-item>-->
        <el-divider content-position="left">调度信息</el-divider>
        <el-row>
          <el-col :span="24">
            <div class="grid-content bg-purple-dark">
              <el-form-item label="调度类型" prop="scheduleType">
                <el-radio v-for="(item, index) in dictList('scheduling_type')" :key="index" v-model="readerForm.scheduleType" :label="item.value" @change="handleRadioChange">
                  {{ item.label }}
                </el-radio>
              </el-form-item>

              <el-form-item label="调度时间" prop="scheduleTime" v-if="readerForm.scheduleType == '0'">
                <el-date-picker v-model="readerForm.scheduleTime" type="datetime" placeholder="选择日期时间"> </el-date-picker>
              </el-form-item>
            </div>
          </el-col>
          <el-col :span="24" v-if="readerForm.scheduleType == '1'">
            <el-form-item label="生效日期：" prop="isIncrement">
              <el-date-picker @change="handleDateRangeChange" v-model="dateRange" type="datetimerange" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期"> </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="24" v-if="readerForm.scheduleType == '1'">
            <el-form-item label="调度时间：" prop="cronExpression">
              <el-input v-model="readerForm.cronExpression" @focus="dialogCron = true" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="falseFun">取 消</el-button>
        <el-button type="primary" @click="trueFun">确 定</el-button>
      </span>
    </el-dialog>

    <el-dialog title="设置执行策略" :visible.sync="dialogCron" :append-to-body="true" :close-on-click-modal="false">
      <Crontab @fill="getStr" @hide="dialogCron = false"></Crontab>
    </el-dialog>
  </div>
</template>

<script>
import { fetchMasterdataDirectoryList } from '@/api/masterdata/masterdataDirectory'
import dayjs from 'dayjs'
import { getorcleDatajson } from '@/api/database'
import Crontab from '@/components/Crontab/index.vue'

export default {
  components: { Crontab },
  data() {
    return {
      arr: [],
      dialogCron: false,
      dateRange: [],
      indexlist: [],
      sumterdialogVisible: false,
      treeList: [],
      upResName: '',
      temp: {},
      treeProps: {
        children: 'children',
        label: 'label',
      },
      treeQuery: {
        tableName: undefined,
        page: 1,
        limit: this.$store.getters.defaultPageSize,
        ancestralId: '7',
      },
      readerForm: {
        jobName: undefined,
        directoryId: undefined,
        description: undefined,
        scheduleType: '0',
        cronExpression: undefined,
        rerunTime: undefined,
        scheduleTime: '', //调度时间
      },
      listQuery: {
        jobName: undefined,
        dbType: undefined,
        executeStatus: undefined,
        checkStatus: undefined,
        isSync: undefined,
        directoryId: '',
        page: 1,
        limit: this.$store.getters.defaultPageSize,
      },
    }
  },
  created() {
    this.getTreeList()
  },
  methods: {
    getStr(str) {
      this.temp.cronExpression = str
      this.readerForm.cronExpression = str
    },
    handleDateRangeChange() {
      // 处理日期范围选择器的值变化事件
      if (Array.isArray(this.dateRange) && this.dateRange.length === 2) {
        this.readerForm.effectTime = this.dateRange[0]
        this.readerForm.failureTime = this.dateRange[1]
        console.log('开始日期:', this.startDate)
        console.log('结束日期:', this.endDate)
      } else {
        this.startDate = ''
        this.endDate = ''
      }
    },
    trueFun() {
      this.dataFun({ ...this.indexlist, ...{ ...this.readerForm } })
    },
    dataFun(param1) {
      if (param1.isIncrement == '0') {
        this.arr = {
          // // 数据来源
          sourceDatasourceName: param1.sourceName,
          sourceDatasourceId: param1.sourceId,
          description: param1.description,
          directoryId: param1.directoryId,
          jobName: param1.jobName,
          type: param1.isIncrement,
          cronExpression: param1.cronExpression,
          effectTime: dayjs(param1.effectTime).format('YYYY-MM-DD'),
          failureTime: dayjs(param1.failureTime).format('YYYY-MM-DD'),
        }
        this.list = []
        param1.tableId.forEach((v, i) => {
          let obj = {}
          obj['sourceTableId'] = v.id
          this.list.push(obj)
        })
      } else if (param1.isIncrement == '1') {
        this.arr = {
          // // 数据来源
          sourceDatasourceName: param1.sourceName,
          sourceDatasourceId: param1.sourceId,
          description: param1.description,
          jobName: param1.jobName,
          type: param1.isIncrement,
          startIndex: param1.startindex,
          endIndex: param1.endindex,
          cronExpression: param1.cronExpression,
          effectTime: dayjs(param1.effectTime).format('YYYY-MM-DD'),
          failureTime: dayjs(param1.failureTime).format('YYYY-MM-DD'),
        }
        this.list = []
        param1.tableId.forEach((v, i) => {
          let obj = {}
          obj['sourceTableId'] = v.id
          this.list.push(obj)
        })
      } else if (param1.isIncrement == '2') {
        this.arr = {
          // // 数据来源
          effectTime: dayjs(param1.effectTime).format('YYYY-MM-DD'),
          failureTime: dayjs(param1.failureTime).format('YYYY-MM-DD'),
          sourceDatasourceName: param1.sourceName,
          sourceDatasourceId: param1.sourceId,
          description: param1.description,
          jobName: param1.jobName,
          type: param1.isIncrement,
          cronExpression: param1.cronExpression,
          startTime: dayjs(param1.dateRange[0]).format('YYYY-MM-DD'),
          endTime: dayjs(param1.dateRange[1]).format('YYYY-MM-DD'),
        }
        this.list = []
        param1.tableId.forEach((v, i) => {
          let obj = {}
          obj['sourceTableId'] = v.id
          obj['timeColumn'] = v.onlyColumn
          this.list.push(obj)
        })
      }

      getorcleDatajson({
        json: JSON.stringify({
          ...this.arr,
          tableList: this.list,
        }),
      }).then((res) => {
        this.sumterdialogVisible = false
        this.$emit('offfun')
      })
    },
    falseFun() {
      this.off()
      this.$emit('offfun')
    },
    //节点点击事件
    handleNodeClick(data) {
      // this.readerForm.jobGroup = node.label;
      // this.treeVisible = false; // 隐藏树

      // 这里主要配置树形组件点击节点后，设置选择器的值；自己配置的数据，仅供参考
      this.upResName = data.name
      this.readerForm.directoryId = data.id

      // 选择器执行完成后，使其失去焦点隐藏下拉框的效果
      this.$refs.selectUpResId.blur()
    },
    handleClear() {
      // 将选择器的值置空
      this.upResName = ''
      this.readerForm.directoryId = ''
    },
    getTreeList() {
      this.listLoading = true
      fetchMasterdataDirectoryList(this.treeQuery).then((response) => {
        if (response.data.code == 200) {
          this.treeList = response.data.data
          if (this.treeList.length > 0) {
            this.listQuery.directoryId = this.treeList[0].children[0].id
            this.currentNodekey = this.treeList[0].id
          }
          this.listLoading = false
        } else {
          this.$message.error(response.data.msg)
        }
        this.listLoading = false
      })
    },
    // 弹框开按钮
    on(item) {
      this.indexlist = item
      this.sumterdialogVisible = true
      this.$emit('offmodellodin')
    },
    // 弹框关按钮
    off() {
      this.sumterdialogVisible = false
    },
    handleRadioChange(value) {
      // 处理选项变化事件
      console.log('选项发生变化，新值为：', value)
    },
  },
}
</script>

<style lang="scss" scoped>
.el-dialog {
  z-index: 3000 !important;
}
</style>
